import { AfterViewChecked, Component, ElementRef, EventEmitter, Injector, Output, OnInit, ViewChild, Input } from '@angular/core';
import { AppConsts } from '@shared/AppConsts';
import { ActivatedRoute } from '@angular/router';
import { AppComponentBase } from '@shared/common/app-component-base';
import { ProfileServiceProxy, TaskServiceProxy, WorkflowServiceProxy, OutsourcingWorkflowServiceProxy, ChooseSupplierViewModel, SupplierQuotationServiceProxy, OutsourcingServiceProxy, UserServiceProxy, ProcessingDeliveryDto, ProcessingDeliveryViewDto, ProcessingOutPutDto, SelectItemDto } from '@shared/service-proxies/service-proxies';
import { ModalDirective } from 'ngx-bootstrap';
import * as _ from 'lodash';
import { Paginator } from 'primeng/components/paginator/paginator';
import { Table } from 'primeng/components/table/table';
import { PrimengTableHelper } from 'shared/helpers/PrimengTableHelper';
import { SelectItem } from 'primeng/api';
import { forEach } from '@angular/router/src/utils/collection';

@Component({
    selector: 'app-ChooseSupplier',
    templateUrl: './ChooseSupplier.component.html',
    styleUrls: ['./ChooseSupplier.component.css']
})
export class ChooseSupplierComponent extends AppComponentBase implements OnInit {

    @ViewChild('createOrEditModal') modal: ModalDirective;
    @ViewChild('paginator') paginator: Paginator;
    @ViewChild('taskdataTable') taskdataTable: Table;
    @ViewChild('dataTable') dataTable: Table;

    @Input() workflowid: any;
    @Output() out = new EventEmitter();

    isLoading = true;
    rows: number;
    canvasWidth: number;

    active = false;
    saving = false;
    _processingDeliveryDto: ProcessingDeliveryDto = new ProcessingDeliveryDto();
    _processingDeliveryViewDto: ProcessingDeliveryViewDto[];
    detailsprimengTableHelper: PrimengTableHelper;

    workflow: any;
    datatablevalues: ChooseSupplierViewModel[];
    clonedOutsourcings: { [s: number]: ChooseSupplierViewModel; } = {};
    suppliers: [];
    supplierItems: SelectItem[] = new Array<SelectItem>();
    choseAyy = new Array();
    choseItem = [];
    ngOnInit(): void {
        console.log(this.workflowid);
        this.initForm();
    }
    constructor(injector: Injector,
        private route: ActivatedRoute,
        private _OutsourcingWorkFlowServiceProxy: OutsourcingWorkflowServiceProxy,
        private _taskServiceProxy: TaskServiceProxy,
        private _userServiceProxy: UserServiceProxy,
        private _outsouringServiceProxy: OutsourcingServiceProxy,
        private _supplierQuotationServiceProxy: SupplierQuotationServiceProxy,
        private _workflowService: WorkflowServiceProxy) {
        super(injector);
        this.detailsprimengTableHelper = new PrimengTableHelper();

    }

    initForm(): void {
        this._OutsourcingWorkFlowServiceProxy.getOutsourcingWorkFlow(this.workflowid).subscribe(resultdata => {
            this.workflow = resultdata.workflowDto;
            this.suppliers = this.workflow.supplierUnit.split(',');
            this.suppliers.forEach(element => {
                console.log(element);
                console.log(this.supplierItems);
                this.supplierItems.push({ label: element, value: element });
            });
            this.canvasWidth = this.suppliers.length * 230;
            console.log(this.canvasWidth)
            this._outsouringServiceProxy.getOutsourcingsForChooseSupplier(this.workflowid).subscribe(dto => {
                this.datatablevalues = dto;
                this.rows = dto.length;
                console.log(dto);
                this.active = true;
                this.isLoading = false;
            })

        })
    }

    getSupplierQuotation(suppliername: string, rowindex: number): string {
        let currentD = this.datatablevalues[rowindex];
        let quotation = currentD.quotations.find((element) => (element.supplier === suppliername));
        if (quotation) {

            return quotation.quotation;
        }
        return '-';
    }
    audityes(): void {
        this.choseAyy = new Array();
        this.choseItem = new Array();
        this.datatablevalues.forEach(element => {
            console.log(element.supplierName)
            if (element.supplierName === undefined || element.supplierName === null) {
                this.notify.info(element.taskName + '未选择供方！');
                this.choseAyy.push('0');
                this.choseItem.push(element.taskName + '未选择供方！');
                return;
            }
        });
        console.log(this.datatablevalues);
        console.log(this.choseItem);
        let index = this.choseAyy.indexOf('0');
        console.log(index);
        // tslint:disable-next-line: triple-equals
        if (index != -1) {
            this.notify.info(this.choseItem[index]);
            return;
        }

        this._OutsourcingWorkFlowServiceProxy.outsourcingFlow_ChooseSupplier(this.workflowid,'ok').subscribe(dto => {
            console.log(dto);
            this.out.emit(dto);
        });
    }

    auditno(): void {
        this._OutsourcingWorkFlowServiceProxy.outsourcingFlow_ChooseSupplier(this.workflowid,'no').subscribe(dto => {
            console.log(dto);
            this.out.emit(dto);
        });
    }

    closemodel(): void {
        this.datatablevalues = [];
        this.clonedOutsourcings = {};
        this.out.emit('关闭');
    }

    onRowEditInit(quotationmodel: ChooseSupplierViewModel) {
        console.log(quotationmodel);
        this.clonedOutsourcings[quotationmodel.taskForModelId.toString()] = { ...quotationmodel };
    }

    onRowEditSave(quotationmodel: ChooseSupplierViewModel) {
        console.log(quotationmodel);
        if (quotationmodel.outsourcingAmount > 0) {
            delete this.clonedOutsourcings[quotationmodel.taskForModelId.toString()];

            this._outsouringServiceProxy.updateOutsourcingChooseSupplier(quotationmodel).subscribe(result => {
                if (result === "ok") {
                    this.notify.info(this.l('SavedSuccessfully'));
                }
            })
        } else {
            this.notify.info('申请数量不能小于0');
        }
    }

    onRowEditCancel(quotationmodel: ChooseSupplierViewModel, index: number) {
        console.log(this.clonedOutsourcings[quotationmodel.taskForModelId.toString()]);
        this.datatablevalues[index] = this.clonedOutsourcings[quotationmodel.taskForModelId.toString()];
        delete this.datatablevalues[quotationmodel.taskForModelId];
    }

    changesuppler(evt, quotationmodel: ChooseSupplierViewModel) {
        console.log(evt);
        quotationmodel.supplierName = evt.value;
    }
}
